package cc.lzmsh.controller;

import cc.lzmsh.pojo.Article;
import cc.lzmsh.pojo.result.PageBean;
import cc.lzmsh.pojo.result.Result;
import cc.lzmsh.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * Author:   msh
 * Date:     2024/9/26 下午2:40
 * Description:
 */

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    /**
     * 新增文章(发布文章)
     */
    @PostMapping
    public Result addArticle(@RequestBody Article article) {
        return articleService.addArticle(article);
    }

    /**
     * 根据条件查询文章,带分页
     */
    @GetMapping
    public Result<PageBean<Article>> list(Integer pageNum,
                                 Integer pageSize,
                                 @RequestParam(required = false) String categoryId,
                                 @RequestParam(required = false) String state) {
        return articleService.list(pageNum, pageSize, categoryId, state);
    }

    /**
     * 根据ID获取文章详细信息
     */
    @GetMapping("/detail/{id}")
    public Result getArticleById(@PathVariable("id") Integer id) {
        return articleService.getArticleById(id);
    }

    /**
     * 更新文章信息
     */
    @PutMapping
    public Result updateArticle(@RequestBody Article article) {
        return articleService.updateArticle(article);
    }

    /**
     * 根据ID删除文章
     */
    @DeleteMapping("/{id}")
    public Result deleteArticle(@PathVariable Integer id) {
        return articleService.deleteArticle(id);
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        return articleService.upload(filename,file.getInputStream());
    }
}
